package com.jetpackframework.http;

import android.util.Log;

import androidx.lifecycle.Lifecycle;

import com.jetpackframework.request.RequestUtil;
import com.jetpackframework.retrofit.ResponseBodyConverter;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.OkHttpRequestBuilder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.OkHttpClient;
import okhttp3.Request;

public class HttpUtil extends RequestUtil<HttpTask,HttpCache> {
    private static HttpUtil instance;
    public List<ResponseBodyConverter<String,?>> responseConverter;

    private void executeWebSocket(HttpTask task) {
        Request request = getRequest(task);
        OkHttpUtils.getInstance().getOkHttpClient().newWebSocket(request,task.getWebSocketListener());
    }

    private HttpUtil(){
        responseConverter = new ArrayList<>();
    }

    @Override
    protected void execTask(HttpTask task) {
        if (task.getLifecycle().getCurrentState() == Lifecycle.State.STARTED || task.getLifecycle().getCurrentState() == Lifecycle.State.RESUMED || task.getLifecycle().getCurrentState() == Lifecycle.State.CREATED) {
            if (task.getGetBuilder() != null) {
                execute(task, task.getGetBuilder());
            } else if (task.getRequest() != null) {
                execute(task.getRequest(), task);
            } else if (task.getPostFormBuild() != null) {
                execute(task, task.getPostFormBuild());
            } else {
                executeWebSocket(task);
            }
        }else {
            Log.e(getClass().getSimpleName(),"task url:"+task.getUrl()+" lifecycle expired!");
        }
    }

    @Override
    protected HttpCache getCache() {
        return HttpCache.getCache();
    }

    public synchronized static HttpUtil getInstance(){
        if (instance == null){
            instance = new HttpUtil();
        }
        return instance;
    }

    public void init(OkHttpClient okHttpClient){
        OkHttpUtils.initClient(okHttpClient);
    }

    private <T> void execute(final Request request, final HttpTask<T> httpParams) {
        Log.e("TAG",httpParams.toString());
        if (httpParams.getNetListener() != null)
            httpParams.getNetListener().onBefore(request,0);
        OkHttpUtils.getInstance().getOkHttpClient().newCall(request).enqueue(new CallBack<T>(httpParams));
    }

    private Request getRequest(HttpTask params) {
        Request.Builder builder = new Request.Builder();
        builder.url(params.getUrl());
        return builder.build();
    }
    private <T> void execute(final HttpTask<T> httpParams, OkHttpRequestBuilder build) {
        build.build().execute(new CallBack<T>(httpParams));
    }
    public void addResponseConverter(ResponseBodyConverter<String,?> converter){
        responseConverter.add(converter);
    }
}
